﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GoodMan.Infrastructure.Entities.Entity;
using GoodMan.Infrastructure.Entities;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;
using GoodMan.Tool.Configration;

namespace GoodMan.Portal.Biz
{
    public class RebateReportBiz
    {
        public static List<RebateReport> GetLastMonthOrders()
        {
            string year = DateTime.Now.AddMonths(-1).Year.ToString();
            string month = DateTime.Now.AddMonths(-1).Month.ToString().PadLeft(2, '0');

            var count = new RebateReport().Count(c => c.Year == year && c.Month == month);
            if (count <= 0)
            {
                using (Context ctx = new Context())
                {

                    string startDate = DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01 00:00:00";
                    string endDate = DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00";
                    string sql = @"select a.UserName,a.RealName,a.FloorId,a.RebateLevel,c.successOrder,c.successmoney,d.cancelOrder from T_User a
                            left join (select HandleUser,COUNT(*) as successOrder,SUM(TotalPrice) as successmoney from T_Order where Status=4 and OrderDate>=@startDate and OrderDate<@endDate group by HandleUser) c on a.UserName=c.HandleUser
                            left join (select HandleUser,COUNT(*) as cancelOrder from T_Order where Status=5 and OrderDate>=@startDate and OrderDate<@endDate group by HandleUser) d on a.UserName=d.HandleUser
                            
                            where a.SystemRole=12";

                    var datatable = ctx.ExcuteSQL(sql,
                        new SqlParameter("@startDate", startDate),
                         new SqlParameter("@endDate", endDate)
                        );

                    List<RebateReport> data = null;
                    if (datatable != null && datatable.Rows.Count > 0)
                    {
                        data = new List<RebateReport>();
                        foreach (DataRow row in datatable.Rows)
                        {
                            var rebateReport = new RebateReport()
                            {
                                DormitoryId = int.Parse(row["FloorId"].ToString()),
                                user = new User() { RealName = row["RealName"].ToString(), RebateLevel = row["RebateLevel"].ToString() },
                                UserName = row["UserName"].ToString(),
                                SuccessOrders = int.Parse(row["successOrder"].ToString() == "" ? "0" : row["successOrder"].ToString()),
                                SuccessMoney = decimal.Parse(row["successmoney"].ToString() == "" ? "0" : row["successmoney"].ToString()),
                                CancelOrders = int.Parse(row["cancelOrder"].ToString() == "" ? "0" : row["cancelOrder"].ToString()),
                                Rebate = GetRebatePoint(row["RebateLevel"].ToString())
                            };
                            data.Add(rebateReport);
                        }
                    }
                    return data;
                }
            }
            else
            {
                using (Context ctx = new Context())
                {
                    var data = (from c in ctx.RebateReport
                                join d in ctx.User
                                on c.UserName equals d.UserName
                                where c.Year == year && c.Month == month
                                select new { c, d }
                              )
                              .ToList()
                              .Select(e => new RebateReport().Set(e.c).LoadUser(e.d)).ToList();
                    return data;
                }

            }


        }

        public static ItemListBox<RebateReport> GetRebateReport(string startYear, string startMonth, string endYear, string endMonth, int page = 0, int pageSize = 20)
        {
            DateTime date = DateTime.Now.AddMonths(-1);
            if (startYear == null || startYear == "")
            {
                startYear = date.Year.ToString();
            }
            if (startMonth == null || startMonth == "")
            {
                startMonth = date.Month.ToString().PadLeft(2, '0');
            }
            if (endYear == null || endYear == "")
            {
                endYear = date.Year.ToString();
            }
            if (endMonth == null || endMonth == "")
            {
                endMonth = date.Month.ToString().PadLeft(2, '0');
            }
            //DateTime startDate = DateTime.Parse(startYear+"-"+startMonth+"-01");
            //DateTime endDate = DateTime.Parse(endYear + "-" + endMonth + "-01");
            //int totalMonth = endDate.Year * 12 + endDate.Month - startDate.Year * 12 - startDate.Month+1;
            int count = new RebateReport().Count(c => (c.Year + "-" + c.Month).CompareTo((endYear + "-" + endMonth)) <= 0 && (c.Year + "-" + c.Month).CompareTo((startYear + "-" + startMonth)) >= 0);
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.RebateReport
                            join d in ctx.User
                            on c.UserName equals d.UserName
                            join f in ctx.Dormitory
                            on d.FloorId equals f.Id
                            where (c.Year + "-" + c.Month).CompareTo((endYear + "-" + endMonth)) <= 0 &&
                            (c.Year + "-" + c.Month).CompareTo((startYear + "-" + startMonth)) >= 0
                            orderby c.Year descending, c.Month descending
                            select new { c, d, f }
                          )
                          .Skip(page * pageSize)
                           .Take(pageSize)
                          .ToList()
                          .Select(e => new RebateReport().Set(e.c).LoadUser(e.d).LoadDormitory(e.f)).ToList();
                return new ItemListBox<RebateReport>(data).BuildPage(
                    count, page, pageSize, new PageParameter() { Style = "workspace" }); ;
            }

        }


        public static decimal GetRebatePoint(string level)
        {
            var commission = SiteResource.Commissions.FirstOrDefault(c => c.value == level);
            decimal point = 0;
            if (commission != null)
            {
                point = commission.point;
            }
            return point;
        }

        public static ItemListBox<RebateReport> MyRebate(int page = 0)
        {
            string userName=System.Web.HttpContext.Current.User.Identity.Name;
            var count = new RebateReport().Count(c => c.UserName == userName);
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.RebateReport
                            where c.UserName == userName
                            orderby c.Year, c.Month descending
                            select c)
                           .Skip(page * 12)
                           .Take(12)
                           .ToList()
                            .Select(d => new RebateReport().Set(d)).ToList();
                var list = new ItemListBox<RebateReport>(data).BuildPage(
                  count, page, 12, new PageParameter() { Style = "workspace" });
                return list;
                          
            }
        }
    }
}
